package com.sise.foodplatform.controller;

import com.alibaba.fastjson.JSON;
import com.sise.foodplatform.pojo.QueryInfo;
import com.sise.foodplatform.pojo.User;
import com.sise.foodplatform.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

@Api(description="用户管理")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "所有用户列表")
    @RequestMapping("/allUser")
    public String getUserList(QueryInfo queryInfo){
        //获取最大列表数和当前编号
        int numbers = userService.getUserCounts("%" + queryInfo.getQuery() + "%");
        int pageStart = (queryInfo.getPageNum() - 1) * queryInfo.getPageSize();
        List<User> users = userService.getAllUser("%" + queryInfo.getQuery() + "%", pageStart, queryInfo.getPageSize());
        HashMap<String, Object> res = new HashMap<>();
        res.put("numbers",numbers);
        res.put("users",users);
        String res_string = JSON.toJSONString(res);
        return res_string;
    }

    @ApiOperation(value = "更新用户状态")
    @RequestMapping("/userState")
    public String updateState(@RequestParam("id")Integer id,@RequestParam("state")Boolean state){
        int i = userService.updateState(id, state);
        return i>0?"success":"error";
    }

    @ApiOperation(value = "新增用户")
    @RequestMapping("/addUser")
    public String addUser(@RequestBody User user){
        user.setRole("用户");
        user.setState(false);
        int i = userService.addUser(user);
        return i>0?"success":"error";
    }

    @ApiOperation(value = "根据ID删除用户")
    @RequestMapping("/deleteUser")
    public String deleteUser(@ApiParam(name = "id", value = "用户ID", required = true) int id){
        int i = userService.deleteUser(id);
        return i>0?"success":"error";
    }

    @ApiOperation(value = "根据ID获取用户")
    @RequestMapping("/getUpdate")
    public String getUpdateUser(@ApiParam(name = "id", value = "用户ID", required = true) int id){
        User user = userService.getUpdateUser(id);
        String s = JSON.toJSONString(user);
        return s;
    }

    @ApiOperation(value = "编辑用户")
    @RequestMapping("/editUser")
    public String editUser(@RequestBody User user){
        int i = userService.editUser(user);
        return i>0?"success":"error";
    }
}
